﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using eTerm.MsSql.DbProvider;
using eTerm.Platform.Common;
using eTerm.Platform.Business;
using System.IO;

namespace eTerm.Platform.Web.PNR
{
    public partial class DetrQuery : BasePage
    {

        protected override string PageCode
        {
            get { return @"YHYEW"; }
        }

        protected override void InitPageLoad()
        {
            Enum.GetValues(typeof(DetrStatus)).Cast<int>().ToList().ForEach(l => {
                if (GetAttribute((DetrStatus)l, typeof(QueryAttribute)) != null) {
                    ListItem item = new ListItem(string.Format(@"{0}<span style='display:none;'>{1}</span>", GetDescription((DetrStatus)l),l), l.ToString()) { Selected =l==(int)DetrStatus.OPENFORUSE };
                    //item.Attributes.Add("VOBJECT", l.ToString());
                    chkStatus.Items.Add(item);
                }
               
            });
            dlUploader.DataSource = new List<SysUser>() { new SysUser() { UserId =0, DisplayName = @"  全  部  " } }.Union(SysUser.All().Where(l=>l.CompanyCode==CurrentUser.CompanyCode).ToList());
            //SysUser.All().Where(l => l.CompanyCode == CurrentUser.CompanyCode).ToList().ForEach(l => {
            //    dlUploader.Items.Add(new ListItem(l.DisplayName, l.UserId.ToString()));
            //});

            dlUploader.DataTextField = @"DisplayName";
            dlUploader.DataValueField = @"UserId";
            dlUploader.DataBind();
            QueryData();
        }


        private void QueryData() {
            int Status = 0;
            int PageID = AspNetPager1.CurrentPageIndex;
            int PageSize = AspNetPager1.PageSize;
            int uid = int.Parse(dlUploader.SelectedValue);
            chkStatus.Items.Cast<ListItem>().Where(l => l.Selected).ToList().ForEach(l =>
            {
                Status = Status | int.Parse(l.Value);
            });

            var sql = PnrDetr.All().Join(SysUser.All().Where(l=>l.CompanyCode==CurrentUser.CompanyCode), l => l.UserId, r => r.UserId, (l, r) => new { r.UserId, r.UserNo, r.DisplayName, l.Id, l.DetrDescription, l.ProcessDate, l.StatusId, l.TicketDate, l.TicketNo }).Where(l => (Status & l.StatusId) != 0);

            if (uid != 0)
                sql = sql.Where(l => l.UserId == uid);

            if (!string.IsNullOrEmpty(tbTicketNo.Text.Trim()))
                sql = sql.Where(l => l.TicketNo.Contains(tbTicketNo.Text.Trim()));

            if (!string.IsNullOrEmpty(tbStartDate.Text.Trim()))
                sql = sql.Where(l => l.ProcessDate >= DateTime.Parse(tbStartDate.Text.Trim()));

            if(!string.IsNullOrEmpty(tbEndDate.Text.Trim()))
                sql = sql.Where(l => l.ProcessDate <= DateTime.Parse(tbEndDate.Text.Trim()));

            //var sql01 = sql.Join(SysUser.All(), l => l.UserId, r => r.UserId, (l, r) => new {r.UserId,r.UserNo,r.DisplayName,l.Id,l.DetrDescription,l.ProcessDate,l.StatusId,l.TicketDate,l.TicketNo });

            this.AspNetPager1.RecordCount = sql.Count();
            this.rptDetr.DataSource = sql.Skip((PageID - 1) * PageSize).Take(PageSize).OrderByDescending(l => l.Id);


            this.AspNetPager1.CustomInfoHTML = string.Format("当前第{0}/{1}页 共{2}条记录 每页{3}条", new object[] { this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageCount, this.AspNetPager1.RecordCount, this.AspNetPager1.PageSize });

            this.rptDetr.DataBind();
            this.AspNetPager1.DataBind();
            //InitPageLoad();
        }


        protected void rptDetr_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) {
                LinkButton lnkHistory = e.Item.FindControl(@"lnkHistory") as LinkButton;
                LinkButton lnkComplete = e.Item.FindControl(@"lnkComplete") as LinkButton;
                Literal litStatusName = e.Item.FindControl("litStatusName") as Literal;
                Literal lbDisplayName = e.Item.FindControl(@"lbDisplayName") as Literal;
                HyperLink lnkTicketNo = e.Item.FindControl(@"lnkTicketNo") as HyperLink;

                var detr = e.Item.DataItem;

                lnkComplete.Visible = (int)Get<object>(detr, @"UserId") == UID && ((int)Get<object>(detr, @"StatusId") & ((int)DetrStatus.COMPLETED )) == 0;
                lnkHistory.Visible = (int)Get<object>(detr, @"StatusId") != (int)DetrStatus.PENDDING;
                BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, lnkHistory.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-clock_red'  
}});  
", lnkHistory.ClientID), true);

                BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, lnkComplete.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-save'  
}});  
", lnkComplete.ClientID), true);

                //litStatusName.Text = GetDescription((DetrStatus)detr.StatusId);
                litStatusName.Text = EnumHelper.GetEnumName((DetrStatus)(int)Get<object>(detr, @"StatusId"));
                lnkHistory.OnClientClick = string.Format(@"$.jBox('post:PNRHistory.aspx', {{ajaxData: {{ 'ID':'{0}' }},title:'票号历史信息',width:650,   bottomText: '票号处理历史记录' }});return false;", Get<object>(detr, @"Id"));
                lbDisplayName.Text =string.Format(@"{0}[{1}]", Get<object>(detr, @"DisplayName"),Get<object>(detr,@"UserNo"));
                lnkComplete.OnClientClick = string.Format(@"$.jBox.confirm('确实需要手工完成票号处理？', '票号处理', function(v,h,f){{if(v=='ok'){{ $.post('../ISAPI/SysUserAPI.ashx',{{ ID:{0},Action:'completedetr' }},function(){{ $.jBox.tip('票号 {1} 手工处理成功。', 'success'); $('#{2}').hide(); }}); }}else{{  $.jBox.tip('票号 {1} 手工处理操作已取消。', 'info'); }} }},{{ bottomText: '处理完成后系统将不再自动搜索票号信息' }}); return false;", Get<object>(detr, @"Id"), Get<object>(detr, @"TicketNo"), lnkComplete.ClientID);
                lnkTicketNo.NavigateUrl = string.Format(@"javascript:OpenDetail({0});", Get<object>(detr, @"Id"));
            }
        }


        protected void btnQuery_Click(object sender, EventArgs e) {
            AspNetPager1.CurrentPageIndex = 1;
            QueryData();
        }

        protected override void InitEasyUI()
        {
            BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, btnQuery.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-search'  
}});  
", btnQuery.ClientID), true);

            BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, btnExport.ClientID, string.Format(@"$('#{0}').linkbutton({{   
    iconCls: 'icon-application_side_expand'  
}});  
", btnExport.ClientID), true);

            BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, dlUploader.ClientID, string.Format(@"$('#{0}').combobox();  
", dlUploader.ClientID), true);

            BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, tbEndDate.ClientID, string.Format(@"$('#{0}').datebox();  
", tbEndDate.ClientID), true);

            BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, tbStartDate.ClientID, string.Format(@"$('#{0}').datebox();  
", tbStartDate.ClientID), true);

            BaseRegisterStartupScript<UpdatePanel>(GetUpdatePanel(@"pnlContent") as UpdatePanel, tbStartDate.ClientID, string.Format(@"$('#{0}').datebox();  
", tbStartDate.ClientID), true);

            btnExport.OnClientClick = string.Format(@"javascript:OpenExecl($('#{0}'),$('input[name=""{1}""]'),$('input[name=""{2}""]'),$('#{3}'));return false;", dlUploader.ClientID, tbStartDate.UniqueID, tbEndDate.UniqueID, chkStatus.ClientID);
        }


        protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
        {
            AspNetPager1.CurrentPageIndex = e.NewPageIndex;
            QueryData();
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            string filename = string.Format("票号列表{0}.xls", DateTime.Now.ToString(@"yyyyMMddHHmmss"));
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
            Response.Clear();

            int Status = 0;
            chkStatus.Items.Cast<ListItem>().Where(l => l.Selected).ToList().ForEach(l =>
            {
                Status = Status | int.Parse(l.Value);
            });


            Response.BinaryWrite((new NPOIDetr().ToExcel(string.Empty, dlUploader.SelectedValue == @"0" ? null : int.Parse(dlUploader.SelectedValue) as int?, string.IsNullOrEmpty(tbStartDate.Text.Trim()) ? null : DateTime.Parse(tbStartDate.Text.Trim()) as DateTime?, string.IsNullOrEmpty(tbEndDate.Text.Trim()) ? null : DateTime.Parse(tbEndDate.Text.Trim()) as DateTime?, Status) as MemoryStream).GetBuffer());
            Response.End();
        }


        

         
    }
}
